package com.eelye.util.winui.window;

import com.sun.jna.platform.win32.WinDef.HWND;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WindowFactory {

    private static final Map<String, Class<? extends Window>> clsWindowMap = new HashMap<>();

    static {
        clsWindowMap.put("SysTreeView32", TreeView.class);
        clsWindowMap.put("Edit", Edit.class);
    }

    public static Window buildWindow(HWND hWnd, String clsName) {
        Class<? extends Window> cls = clsWindowMap.get(clsName);
        if (null == cls) {
            return new Window(hWnd);
        }

        Constructor<? extends Window> constructor;
        try {
            constructor = cls.getConstructor(HWND.class, String.class);
            return constructor.newInstance(hWnd, clsName);
        } catch (NoSuchMethodException e) {
            try {
                constructor = cls.getConstructor(HWND.class);
                return constructor.newInstance(hWnd);
            } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
                    | InvocationTargetException e1) {
                throwException(clsName, e1);
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throwException(clsName, e);
        }

        return null;
    }

    private static void throwException(String clsName, Exception e) {
        log.error("创建{}失败。", clsName, e);

        throw new RuntimeException(e);
    }
}
